package org.theSeed.springBase.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.theSeed.base.exp.BuzExp;
import org.theSeed.base.pojo.sysEnum.SysCode;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;

/**
 * spring参数校验工具
 */
public class SpringParamUtil {
    /**
     * 获取验证工具
     * @return
     */
    public static Validator getValidator(){
        return SpringUtil.getBean(Validator.class);
    }

    /**
     * 参数校验
     * @param param
     * @param group
     * @param <T>
     */
    public static <T> void checkParam(T param,Class<?> group){
        List<String> msgList = new ArrayList<>();
        for (ConstraintViolation<T> item : getValidator().validate(param, group)) {
            msgList.add(item.getMessage());
        }
        if (CollectionUtil.isNotEmpty(msgList)){
            throw new BuzExp(SysCode.PARAM_ERR.getCode(),msgList);
        }
    }
}
